#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import datetime
import time
import os
import loger

os.chdir(r'/home/aiot/workspace/EpidemicPreventionProj/EP_autoCleaner')

def getFileCreateDate(filepath):
    t = os.path.getctime(filepath)
    createdate = time.strftime("%Y%m%d", time.localtime(t))

    return createdate


def delByTime(thispath, nowdatestr):
    filecreatetime = getFileCreateDate(thispath)
    if nowdatestr != filecreatetime:
        try:
            os.remove((thispath))
            log.info('cleanJob: remove ' + thispath)
        except:
            log.error('cleanJob: fail to remove ' + thispath)


def cleanTmpFiles(folderpath, str_nowdate):
    '''
    根据文件创建时间，清理指定目录中的文件
    :param folderpath:
    :param str_nowdate:
    :return:
    '''
    nowdatestr = datetime.datetime.now().strftime('%Y%m%d') # 当前日期

    files = os.listdir(folderpath)
    for f in files:
        thispath = os.path.join(folderpath, f)
        if (os.path.isfile(thispath)):
            delByTime(thispath, nowdatestr)


if __name__ == "__main__":
    '''
    永远执行。需要手动启动。
    定时清理可能残留的临时文件
    '''
    publicShareImgTmpFolder = "../EP_imgTmpSpace/"
    log = loger.Log("autoCleaner")
    log.info("start autocleaner")

    while 1:
        # 定时清理任务
        time.sleep(30)
        nowtimestr = datetime.datetime.now().strftime('%H%M')
        if nowtimestr == "1925":  # 每天凌晨3点0分，开始自动清理前一天或更早生成的本地临时文件
            cleanTmpFiles(publicShareImgTmpFolder, nowtimestr)
